/*
动态规划求解：
dp[i][j]为到达点(i, j)时的路径和最小值
由于只能往下或往右走
递推式:
dp[i][j] = min(dp[i-1][j] + dp[i][j-1]) + grid[i][j]

初始情形:
dp[0][0] = grid[0][0]
dp[i][0] = dp[i-1][0] + grid[i][0]
dp[0][j] = dp[0][j-1] + grid[0][j]

*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid)
    {
        int m = grid.size();
        int n = grid[0].size();
        int dp[m][n];
        //initial
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 && j == 0)
                    dp[i][j] = grid[i][j];
                else if (i == 0)
                    dp[i][j] = dp[i][j - 1] + grid[i][j];
                else if (j == 0)
                    dp[i][j] = dp[i - 1][j] + grid[i][j];
                else
                    dp[i][j] = 0;
            }
        }
        //dp
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++)
                dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
        }
        return dp[m - 1][n - 1];
    }
};

int main(int argc, char const* argv[])
{
    Solution temp;
    vector<vector<int>> grid;
    vector<int> a;
    a.push_back(1);
    a.push_back(2);
    grid.push_back(a);
    vector<int> b(2, 1);
    grid.push_back(b);
    cout << temp.minPathSum(grid) << endl;
    return 0;
}